package com.socketeg.demo.socket;


import com.socketeg.demo.myThread.Readmessage;
import com.socketeg.demo.myThread.SendMessage;

import java.io.*;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 客户端
 */
public class Client {
    public static void startClient() throws IOException {
        Socket socket = new Socket();

        //连接 服务器地址
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(), 8500));

        System.out.println("已连接上服务器！");
        try {
            todo(socket);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            socket.close();
            System.out.println("客户端已退出");
        }
    }

    private static void todo(Socket socket) throws IOException {
        // 获取键盘输入流
        InputStream in = System.in;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));

        //获取打印流
        OutputStream outputStream = socket.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);

        // 接收消息
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReaderSocket = new BufferedReader(new InputStreamReader(inputStream));
        Readmessage readmessage = new Readmessage(bufferedReaderSocket);
        readmessage.start();

        // 将键盘输入打印到服务端
        SendMessage sendMessage = new SendMessage(bufferedReader, printStream);
        sendMessage.start();
    }

}
